﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Lm.Common.ExtensionMethods
{
    public static class DataTableExt
    {
        /// <summary>
        /// 获得包含table所有字段的列表
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<string> GetClolumsList(this DataTable dt)
        {
            return (from DataColumn c in dt.Columns
                    select c.ColumnName).ToList();
        }

        /// <summary>
        /// DataTable转换成Model列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <param name="treat">Model与Row互相转换时，如果结构不相同时的处理方式</param>
        /// <returns></returns>
        public static List<T> ToModelList<T>(this DataTable dt, SchemaNotSame treat) where T : IModel, new()
        {
            return (from DataRow r in dt.Rows
                    select r.ToModel<T>(treat)).ToList();
        }

        public static void CheckColumns(this DataTable dt, string[] columnNameList)
        {
            foreach (var n in columnNameList)
            {
                if (dt.Columns.Contains(n) == false)
                { throw new Exception("必须包含列：" + n); }
            }
        }

        public static void RemoveEmptyRows(this DataTable dt)
        {
            var EmptyRows = (from DataRow row in dt.Rows
                             where
                                 row.ItemArray.All(t => t.ToString().IsNullOrBlank())
                             select row).ToList();
            EmptyRows.ForEach(row => dt.Rows.Remove(row));
        }

        public static DataTable Apend(this DataTable source, DataTable dt)
        {
            if (source.SchemaSameWith(dt) == false)
            { throw new Exception("DataTable结构不一致"); }
            foreach (DataRow row in dt.Rows)
            {
                var newRow = source.NewRow();
                row.DataCopyTo(newRow, false);
                source.Rows.Add(newRow);
            }
            return source;
        }

        public static bool SchemaSameWith(this DataTable source, DataTable dt)
        {
            var row1Columns = source.GetClolumsList();
            var row2Columns = dt.GetClolumsList();
            if (row1Columns.SameWith(row2Columns) == false)
            { return false; }
            foreach (var c in row1Columns)
            {
                if (source.Columns[c].DataType != dt.Columns[c].DataType)
                { return false; }
            }
            return true;
        }
    }
}
